#!/usr/bin/perl -w
use strict;
use Win32::DBIODBC;
use Data::Dumper;

my $dbh =new Win32::ODBC("DSN=ebs_DATADUMP");
if (!defined($dbh)) { die "cannot connect ODBC data source"};

my %data;
my %blueprint_to_item_index;

my %chance02; map {$chance02{$_}=1} ("Sin", "Nighthawk", "Damnation", "Hulk", "Paladin", "Kronos","Eos", "Vulture", "Golem", "Astarte", "Redeemer", "Widow", "Vargur", "Panther", "Sleipnir", "Absolution",
                "Claymore") ;
my %chance025; map {$chance025{$_}=1} ( "Onyx", "Ishtar", "Vagabond", "Devoter", "Phobos", "Deimos", "Oneiros", "Broadsword", "Zealot", "Eagle", "Muninn", "Sacrilege", "Cerberus", "Curse", "Crane", "Bustard",
                "Prorator", "Prowler", "Viator", "Occator", "Mastodon", "Impel", "Mackinaw", "Rook", "Rapier", "Falcon", "Huginn", "Pilgrim", "Arazu", "Basilisk", "Lachesis", "Scimitar",
                "Guardian"  );
my %chance03; map {$chance03{$_}=1} ( "Purifier", "Ishkur", "Enyo", "Manticore", "Hound", "Eris", "Flycatcher", "Skiff", "Raptor", "Jaguar", "Rhea", "Nomad", "Anshar", "Helios", "Keres", "Crow", "Cheetah",
                "Crusader", "Malediction", "Anathema", "Buzzard", "Kitsune", "Stiletto", "Taranis", "Ares", "Vengeance", "Wolf", "Nemesis", "Hawk", "Harpy", "Hyena", "Retribution",
                "Heretic", "Sabre", "Sentinel", "Claw", "Ark");

#format data{id} = {
#        id => id;
#        name =? "name";
#        type => "Tech 1|Tech 2"

  #  IT_T1Item: result := 'Tech 1';
  #  IT_T2Item: result := 'Tech 2';
  #  IT_AdvancedMaterial: result := 'Advmat';
  #  IT_T2Component: result := 'Component';
  #  IT_RAM: result := 'RAM';
  #  IT_Tradegoods: result := 'Tradegoods';
  #  IT_Datacore: result := 'Datacore';
  #  IT_Mineral: result := 'Mineral';
  #  IT_CapComponent: result := 'Capcomponent';
  #  IT_CapT2Component: result := 'CapT2component';
  #  IT_Salvage: result := 'Salvage';
  #  IT_DataInterface: result := 'Interface';
  #  IT_Decryptor: result := 'Decryptor';
  #else result := 'n/a';

#        volume => vol
#        invented_to => {id1,id2,...};
#        invented_from => id;
#}

my $get_researchable_blueprints_sql=q{select a.typeID,parentTypeID 
                                        from invMetaTypes a
                                        left join invTypes b on a.parentTypeID=b.typeID
                                        left join invTypes c on a.typeID=c.typeID
                                        inner join invBlueprintTypes d on d.productTypeID=a.typeID
                                        inner join invBlueprintTypes e on e.productTypeID=a.parentTypeID
                                        where metaGroupID=2 and parentTypeID<>27021 and b.published=1 and c.published=1 };
if (defined( $dbh->Sql($get_researchable_blueprints_sql))) { die "error executing sql: " . Win32::ODBC::Error(  ) };

while($dbh->FetchRow())
{
    my %row=$dbh->DataHash();
    
    my $id=$row{typeID};
    my $parent_id=$row{parentTypeID};

    $data{$id}{id}=$id;
    $data{$id}{type}="Tech 2";
    $data{$id}{invented_from}=$parent_id;
    
    $data{$parent_id}{id}=$parent_id;
    $data{$parent_id}{type}="Tech 1";
    
    my $invented_to=$data{$parent_id}{invented_to};
    push @$invented_to, $id;
    $data{$parent_id}{invented_to}=$invented_to;
}


my $get_blueprint_types_sql=q{select blueprintTypeID,productTypeID,productionTime,techLevel,researchCopyTime,researchTechTime,productivityModifier,materialModifier,wasteFactor,maxProductionLimit from invBlueprintTypes};
if (defined( $dbh->Sql($get_blueprint_types_sql))) { die "error executing sql: " . Win32::ODBC::Error(  ) };

while($dbh->FetchRow())
{
    my %row=$dbh->DataHash();
    
    my $id=$row{productTypeID};
    
    if (exists $data{$id})
    {
        $data{$id}{build_time}=$row{productionTime};
#        $data{$id}{type}="Tech " . $row{techLevel};
        $data{$id}{productivity_modifier}=$row{productivityModifier};
        $data{$id}{invention_time}=$row{researchTechTime};
        $data{$id}{copy_time}=$row{researchCopyTime};
        $data{$id}{production_limit}=$row{maxProductionLimit};
        $data{$id}{base_chance}=""; #$row{};
        $data{$id}{waste_factor}=$row{wasteFactor};
        $data{$id}{bluepint_id}=$row{blueprintTypeID};
        $blueprint_to_item_index{$row{blueprintTypeID}}=$id;
        $data{$id}{build_type}="Normal";

        
    }
}

my $get_type_requirements=q{select a.typeID,activityID,requiredTypeID,quantity,damagePerJob,recycle
                            from ramTypeRequirements a
                            left join invTypes b on requiredTypeID=b.typeID
                            left join invGroups c on b.groupID=c.groupID
                            where c.categoryID <> 16};
if (defined( $dbh->Sql($get_type_requirements))) { die "error executing sql: " . Win32::ODBC::Error(  ) };

while($dbh->FetchRow())
{
    my %row=$dbh->DataHash();
    
    my $bpid=$row{typeID};
    my $id=$blueprint_to_item_index{$bpid};
    my $activity=$row{activityID};
    my $required=$row{requiredTypeID};
    
    if ($id && exists $data{$id} && ($activity==1 || $activity==8 || $activity==5) )
    {
        if ($data{$id}{type} ne "Tech 1" && $data{$id}{type} ne "Tech 2") { next; }
        
        if ($activity==1) { $activity="Manufacturing" }
        elsif ($activity==8) { $activity="Invention" }
        elsif ($activity==5) { $activity="Copying" };
        
        $data{$id}{used}{$activity}{$required}{quantity}=$row{quantity};
        $data{$id}{used}{$activity}{$required}{damagePerJob}=int($row{damagePerJob}*100)/100;
        $data{$id}{used}{$activity}{$required}{recycle}=$row{recycle};
        
        my $used_in=$data{$required}{used_in}{$activity};
        push @$used_in,$id;
        $data{$required}{used_in}{$activity}=$used_in;
        $data{$required}{id}=$required;
        
        my $invention_type;
        my $race;
        
        if ($activity eq "Invention")
        {
            if    ($required==25553) { $invention_type="Normal"; $race="Minmatar"; } #Cryptic Data Interface
            elsif ($required==25554) { $invention_type="Normal"; $race="Amarr"; } #Occult Data Interface
            elsif ($required==25555) { $invention_type="Normal"; $race="Caldari"; } #Esoteric Data Interface
            elsif ($required==25556) { $invention_type="Normal"; $race="Gallente";  } #Incognito Data Interface
            elsif ($required==25851) { $invention_type="Ship"; $race="Amarr"; } #Occult Ship Data Interface
            elsif ($required==25853) { $invention_type="Ship"; $race="Caldari"; } #Esoteric Ship Data Interface
            elsif ($required==25855) { $invention_type="Ship"; $race="Gallente"; } #Incognito Ship Data Interface
            elsif ($required==25857) { $invention_type="Ship"; $race="Minmatar";  } #Cryptic Ship Data Interface
            elsif ($required==26597) { $invention_type="Rig"; $race="Minmatar";  } #Cryptic Tuner Data Interface
            elsif ($required==26599) { $invention_type="Rig"; $race="Caldari"; } #Esoteric Tuner Data Interface
            elsif ($required==26601) { $invention_type="Rig"; $race="Gallente";  } #Incognito Tuner Data Interface
            elsif ($required==26603) { $invention_type="Rig"; $race="Amarr"; } #Occult Tuner Data Interface        
            
            if ($invention_type)
            {
                $data{$id}{invention_type}=$invention_type;
                $data{$id}{invention_race}=$race;
            }
            
            if ($invention_type && $invention_type eq "Ship")
            {
                $data{$id}{build_type}="Ship";
                
                for my $i (@{$data{$id}{invented_to}})
                {
                    $data{$i}{build_type}="Ship";
                };
            }
        }
        
      
#        
        
    }

}

my $get_type_materials=q{select typeID,materialTypeID,quantity from invTypeMaterials};
if (defined( $dbh->Sql($get_type_materials))) { die "error executing sql: " . Win32::ODBC::Error(  ) };

while($dbh->FetchRow())
{
    my %row=$dbh->DataHash();

    my $id=$row{typeID};
    my $required=$row{materialTypeID};
   
    if (exists $data{$id})
    {
        #if (!defined($data{$id}{type}) || ($data{$id}{type} ne "Tech 1" && $data{$id}{type} ne "Tech 2")) { next; }

        $data{$id}{used}{"Manufacturing"}{$required}{quantity}=$row{quantity};
        $data{$id}{used}{"Manufacturing"}{$required}{recycle}=-1;
        $data{$id}{used}{"Manufacturing"}{$required}{damagePerJob}=1;
        
        $data{$required}{id}=$required;
        my $used_in=$data{$required}{used_in}{"Manufacturing"};
        push @$used_in,$id;
        $data{$required}{used_in}{"Manufacturing"}=$used_in;
    }
}

for my $id (keys %data)
{
   
    for my $req_id (keys %{$data{$id}{used}{"Manufacturing"}})
    {
        if ($data{$id}{used}{"Manufacturing"}{$req_id}{recycle} eq 1)
        {
            for my $material (keys %{$data{$req_id}{used}{"Manufacturing"}})
            {
                if ($data{$id}{used}{"Manufacturing"}{$material}{quantity})
                {
                    $data{$id}{used}{"Manufacturing"}{$material}{quantity} = $data{$id}{used}{"Manufacturing"}{$material}{quantity} - $data{$req_id}{used}{"Manufacturing"}{$material}{quantity};
                }
                
            }
        }
    }
    
    for my $req_id (keys %{$data{$id}{used}{"Manufacturing"}})
    {
        if ($data{$id}{used}{"Manufacturing"}{$req_id}{quantity} <= 0) { delete $data{$id}{used}{"Manufacturing"}{$req_id}; }
    }
}




my $get_item_names_sql=q{select typeID,typeName,volume,portionSize,raceID,marketGroupID,a.groupID,groupName from invTypes a left join invGroups b on b.groupID=a.groupID where a.published=1};
if (defined( $dbh->Sql($get_item_names_sql))) { die "error executing sql: " . Win32::ODBC::Error(  ) };

while($dbh->FetchRow())
{
    my %row=$dbh->DataHash();
    
    my $id=$row{typeID};
    my $name=$row{typeName};
    my $volume=int($row{volume}*10000)/10000;
    my $race=$row{raceID};
    my $market=$row{marketGroupID};
    
    if     ($race eq "1") { $race="Caldari" }
    elsif  ($race eq "2") { $race="Minmatar" }
    elsif  ($race eq "4") { $race="Amarr" }
    elsif  ($race eq "8") { $race="Gallente" }
    else { $race="n/a"; }
    
    if (exists $data{$id})
    {
        $data{$id}{name}=$name;
        $data{$id}{volume}=$volume;
        $data{$id}{race}=$race;
        $data{$id}{portion_size}=$row{portionSize};

        my $found=1;

        if   ($market == 499) { $data{$id}{type}="Advmat"; }
        elsif ($market >= 802 && $market <= 805) { $data{$id}{type}="Component"; }
        elsif ($market == 398) { $data{$id}{type}="RAM"; }
        elsif ($market == 20) { $data{$id}{type}="Tradegoods"; }
        elsif ($market == 966) { $data{$id}{type}="Datacore"; }  
        elsif ($market == 18) { $data{$id}{type}="Mineral"; } 
        elsif ($market == 781) { $data{$id}{type}="Capcomponent"; }   
        elsif ($market >= 1099 && $market <= 1102) { $data{$id}{type}="CapT2component"; } 
        elsif ($market == 942) { $data{$id}{type}="Salvage"; } 
        elsif ($market == 980) { $data{$id}{type}="Interface"; }
        else { $found=0; }
      
        if (!$found && !$data{$id}{type}){ print STDERR "Unknown market categ $market ($name)"; } 
        
        if ($found)
        {
            $data{$id}{build_time}=0;
            $data{$id}{productivity_modifier}=1;
            $data{$id}{invention_time}=0;
            $data{$id}{invention_type}="n/a";
            $data{$id}{invention_race}="n/a";
            $data{$id}{copy_time}=0;
            $data{$id}{production_limit}=0;
            $data{$id}{base_chance}=0;
            $data{$id}{waste_factor}=0;
            $data{$id}{build_type}="Normal";
            $data{$id}{portion_size}=1;
            $data{$id}{usedin_amount}=0;
            $data{$id}{requirement_amount}=0;
        }
        
        $data{$id}{usedin_amount}=exists $data{$id}{invented_to}?scalar @{$data{$id}{invented_to}}:0;

        my $sum=0;
        for my $activity (keys %{$data{$id}{used}} )
        {
             $sum += scalar keys %{$data{$id}{used}{$activity}};
        }
        $data{$id}{requirement_amount}=$sum;
        $data{$id}{invented_amount}=0;
        
        if ($data{$id}{type} eq "Tech 1")
        {
            $data{$id}{base_chance}=0;
        }

        if ($data{$id}{type} eq "Tech 2")
        {
            $data{$id}{invention_type}="n/a";
            $data{$id}{invention_race}="n/a";
            
            if ($data{$id}{build_type} eq "Ship" )
            {
                if (exists $chance02{$name} )
                {
                    $data{$id}{base_chance}=0.2;
                }
                elsif (exists $chance025{$name} )
                {
                    $data{$id}{base_chance}=0.25;
                }
                elsif (exists $chance03{$name} )
                {
                    $data{$id}{base_chance}=0.3;
                }
                else { die "Don't know chance for $name"} 
            }
            else
            {
                $data{$id}{base_chance}=0.4;
            }
            
        }

    }
}


for my $id (sort keys %data)
{
    if (!defined($data{$id}{type}))
    {
        print Dumper \$data{$id};
        die "undef!";
    }
    
    if ($data{$id}{name})
    {
      print     "$data{$id}{name}\t"; 
      print     "$data{$id}{id}\t";
      print     "$data{$id}{type}\t";
      print     "$data{$id}{volume}\t";
      print     "$data{$id}{race}\t";
      print     "$data{$id}{build_time}\t";
      print     "$data{$id}{productivity_modifier}\t";
      print     "$data{$id}{invention_time}\t";
      print     "$data{$id}{invention_type}\t";
      print     "$data{$id}{invention_race}\t";
      print     "$data{$id}{copy_time}\t";
      print     "$data{$id}{production_limit}\t";
      print     "$data{$id}{base_chance}\t";
      print     "$data{$id}{waste_factor}\t";
      print     "$data{$id}{build_type}\t";
      print     "$data{$id}{portion_size}\t";
      print     "$data{$id}{usedin_amount}\t";
      print     "$data{$id}{requirement_amount}\t";
      print     "$data{$id}{invented_amount}\n";
                
      for my $i (@{$data{$id}{invented_to}})
      {
        print "<-\t$i\tNone\t1\t0\t1\t# $data{$i}{name}\n";        
      }
                
      for my $activity (keys %{$data{$id}{used}})
      {
        for my $uid (keys %{$data{$id}{used}{$activity}})
        {
            print     "->\t" ;
            print     "$uid\t" ;
            print     "$activity\t" ;
            print     "$data{$id}{used}{$activity}{$uid}{quantity}\t" ;
            print     "$data{$id}{used}{$activity}{$uid}{recycle}\t" ;
            print     "$data{$id}{used}{$activity}{$uid}{damagePerJob}\t" ;
            print     "# $data{$uid}{name}\n";
        }
        
      }
                      
    }
    
}
